package com.nand.library.base.http;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.callback.AbsCallback;

import java.lang.reflect.Type;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by 孝杰 on 2019/12/17.
 */
public abstract class JsonCallback<T> extends AbsCallback<T> {

    private Type mType;
    private Class<T> clazz;

    public JsonCallback() {
    }

    public JsonCallback(Type type) {
        mType = type;
    }

    public JsonCallback(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T convertResponse(Response response) throws Throwable {

        ResponseBody body = response.body();
        if (body == null) {
            return null;
        }
        T data = null;
        String str = response.body().string();
        if (mType != null) {
            data = JSON.parseObject(str, mType);
        }
        if (clazz != null) {
            data = JSON.parseObject(str, clazz);
            //可以将错误信息在onError中获取到
            //https://github.com/jeasonlzy/okhttp-OkGo/wiki/Callback#callback%E4%BB%8B%E7%BB%8D
        }
        return data;
    }
}
